﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace RegionShotPlugin
{
    public class MouseInput
    {
        // create a mouse over eventstatic int WH_MOUSE_LL = 14;
        private readonly IntPtr hook;
        private readonly HookProc hookProc;

        public MouseInput(bool designMode)
        {
            if (!designMode)
            {
                hookProc = new HookProc(LowLevelMouseProc);
                hook = SetWindowsHookEx(14, hookProc, GetModuleHandle(null), 0);
            }
        }

        public bool LeftBtnDown { get; set; }
        public bool RightBtnDown { get; set; }

        public Point Position { get; set; }

        [DllImport("kernel32.dll")]
        static extern IntPtr GetModuleHandle(string moduleName);

        [DllImport("user32.dll")]
        static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll")]
        public static extern int UnhookWindowsHookEx(IntPtr hhook);

        [DllImport("user32.dll")]
        static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, uint wParam, IntPtr lParam);

        public event EventHandler MouseDown;
        public void OnMouseDown(object sender, EventArgs data)
        {
            if (MouseDown != null) MouseDown(sender, data);
        }
        public event EventHandler MouseUp;
        public void OnMouseUp(object sender, EventArgs data)
        {
            if (MouseUp != null) MouseUp(sender, data);
        }

        IntPtr LowLevelMouseProc(int nCode, uint wParam, IntPtr lParam)
        {
            // get the current mouse position
            Position = Cursor.Position;

            // leftclick wparam 513
            if (wParam == 513)
            {
                // prev state
                if (LeftBtnDown == false)
                {
                    OnMouseDown(this, null);
                }
                LeftBtnDown = true;
            }
            else if (wParam == 514) // lbutton up
            {
                LeftBtnDown = false;
                OnMouseUp(this, null);
            }

            // Finished with this
            return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
        }

        public void Dispose()
        {
            UnhookWindowsHookEx(hook);
        }

        #region Nested type: HookProc

        delegate IntPtr HookProc(int nCode, uint wParam, IntPtr lParam);

        #endregion
    }
}
